<template>
  <div class="table-container">
    <div class="table-header">
      <h3>历史销售数据</h3>
      <div class="table-actions">
        <el-select v-model="monthsToShow" size="small" class="months-selector">
          <el-option label="最近12个月" :value="12" />
          <el-option label="最近24个月" :value="24" />
          <el-option label="全部数据" :value="0" />
        </el-select>
        <el-button type="primary" size="small" @click="exportToExcel">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>
    
    <el-table
      :data="filteredData"
      style="width: 100%"
      :stripe="false"
      border
      v-loading="loading"
      height="500"
      :header-cell-style="{
        background: 'var(--bg-card-secondary, #191a32)',
        color: 'var(--text-primary, #e0e0ff)',
        fontWeight: '600',
        padding: '12px 8px',
        borderBottom: '2px solid var(--primary-color, #3a36db)'
      }"
      :row-style="{
        background: 'var(--bg-card-darker, #0f1023)',
        borderBottom: '1px solid var(--border-color, #2a2a57)'
      }"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="month" label="月份" width="100" sortable fixed="left">
        <template #default="scope">
          <div class="month-cell">{{ scope.row.month }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="total" label="销售总额" sortable>
        <template #default="scope">
          <div class="amount-cell">¥{{ formatNumber(scope.row.total) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="product_sales" label="产品销售额" sortable>
        <template #default="scope">
          <div class="amount-cell">¥{{ formatNumber(scope.row.product_sales) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="rental_income" label="租赁收入" sortable>
        <template #default="scope">
          <div class="amount-cell">¥{{ formatNumber(scope.row.rental_income) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="order_count" label="订单数量" width="100" sortable>
        <template #default="scope">
          <div class="count-cell">{{ scope.row.order_count }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="mom_growth" label="环比增长" sortable>
        <template #default="scope">
          <div v-if="scope.row.mom_growth !== null" :class="getGrowthClass(scope.row.mom_growth)" class="growth-text">
            <el-icon v-if="scope.row.mom_growth > 0"><ArrowUp /></el-icon>
            <el-icon v-else-if="scope.row.mom_growth < 0"><ArrowDown /></el-icon>
            {{ Math.abs(scope.row.mom_growth).toFixed(1) }}%
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column prop="yoy_growth" label="同比增长" sortable>
        <template #default="scope">
          <div v-if="scope.row.yoy_growth !== null" :class="getGrowthClass(scope.row.yoy_growth)" class="growth-text">
            <el-icon v-if="scope.row.yoy_growth > 0"><ArrowUp /></el-icon>
            <el-icon v-else-if="scope.row.yoy_growth < 0"><ArrowDown /></el-icon>
            {{ Math.abs(scope.row.yoy_growth).toFixed(1) }}%
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column prop="prediction_error" label="预测误差" sortable>
        <template #default="scope">
          <div v-if="scope.row.prediction_error !== null" :class="getErrorClass(scope.row.prediction_error)" class="error-text">
            {{ scope.row.prediction_error > 0 ? '+' : '' }}{{ scope.row.prediction_error.toFixed(1) }}%
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="table-footer">
      <div class="table-summary">
        显示 {{ filteredData.length }} / {{ salesData.length }} 条数据
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Download, ArrowUp, ArrowDown } from '@element-plus/icons-vue';
import * as XLSX from 'xlsx';

const props = defineProps({
  salesData: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  }
});

// 显示月数
const monthsToShow = ref(12);

// 计算过滤后的数据
const filteredData = computed(() => {
  if (!props.salesData || props.salesData.length === 0) return [];
  if (monthsToShow.value === 0) return [...props.salesData];
  
  // 取最新的N个月数据
  const sortedData = [...props.salesData].sort((a, b) => 
    new Date(b.month) - new Date(a.month)
  );
  
  return sortedData.slice(0, monthsToShow.value);
});

// 格式化数字显示
function formatNumber(num) {
  if (num === undefined || num === null) return '-';
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
}

// 获取增长率的样式类
function getGrowthClass(growth) {
  if (growth > 0) return 'positive';
  if (growth < 0) return 'negative';
  return '';
}

// 获取预测误差的样式类
function getErrorClass(error) {
  const absError = Math.abs(error);
  
  if (absError <= 3) return 'excellent';
  if (absError <= 5) return 'good';
  if (absError <= 8) return 'fair';
  return 'poor';
}

// 导出数据到Excel
function exportToExcel() {
  try {
    // 准备导出数据
    const exportData = filteredData.value.map(item => ({
      '月份': item.month,
      '销售总额': formatNumber(item.total),
      '产品销售额': formatNumber(item.product_sales),
      '租赁收入': formatNumber(item.rental_income),
      '订单数量': item.order_count,
      '环比增长': item.mom_growth !== null ? `${item.mom_growth.toFixed(1)}%` : '-',
      '同比增长': item.yoy_growth !== null ? `${item.yoy_growth.toFixed(1)}%` : '-',
      '预测误差': item.prediction_error !== null ? `${item.prediction_error.toFixed(1)}%` : '-'
    }));
    
    // 创建工作簿和工作表
    const worksheet = XLSX.utils.json_to_sheet(exportData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '历史销售数据');
    
    // 生成并下载Excel文件
    XLSX.writeFile(workbook, `销售数据_${new Date().toISOString().slice(0, 10)}.xlsx`);
    
    ElMessage.success('数据导出成功');
  } catch (error) {
    console.error('导出Excel失败:', error);
    ElMessage.error('导出数据失败');
  }
}

// 添加 tableRowClassName 函数
const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
};
</script>

<style>
/* 在文件头部添加全局样式，不使用scoped，以便全局覆盖 */
.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell {
  background-color: var(--bg-card-darker-alt, #171833) !important;
}

.el-table--striped .el-table__body tr td.el-table__cell {
  background-color: var(--bg-card-darker, #0f1023) !important;
}

.el-table tr {
  background-color: transparent !important;
}

.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
  background-color: var(--bg-card-hover, #1e1f3d) !important;
}
</style>

<style scoped>
.table-container {
  background-color: var(--bg-card, #13142a);
  border-radius: 12px;
  border: 1px solid var(--border-color, #2a2a57);
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.3), 0 0 1px rgba(58, 54, 219, 0.3);
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.table-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 5px;
  background: linear-gradient(to right, #3a36db, #00c9ff, #00ffb3);
  z-index: 2;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border-color, #2a2a57);
}

.table-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary, #e0e0ff);
  position: relative;
  padding-left: 12px;
}

.table-header h3::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background: linear-gradient(to bottom, #3a36db, #00c9ff);
  border-radius: 2px;
}

.table-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.months-selector {
  width: 120px;
}

.table-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 12px 20px;
  border-top: 1px solid var(--border-color, #2a2a57);
}

.table-summary {
  font-size: 12px;
  color: var(--text-secondary, #b8b8cc);
}

.growth-text {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 600;
}

.growth-text .el-icon {
  margin-right: 2px;
}

.growth-text.positive {
  color: #00ffb3;
  background-color: rgba(0, 255, 179, 0.1);
}

.growth-text.negative {
  color: #ff5e7b;
  background-color: rgba(255, 94, 123, 0.1);
}

.error-text {
  display: flex;
  justify-content: center;
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 600;
}

.error-text.excellent {
  color: #00ffb3;
  background-color: rgba(0, 255, 179, 0.1);
}

.error-text.good {
  color: #00c9ff;
  background-color: rgba(0, 201, 255, 0.1);
}

.error-text.fair {
  color: #ff9d00;
  background-color: rgba(255, 157, 0, 0.1);
}

.error-text.poor {
  color: #ff5e7b;
  background-color: rgba(255, 94, 123, 0.1);
}

/* 自定义单元格样式 */
.month-cell {
  font-weight: 600;
  color: var(--text-primary, #e0e0ff);
}

.amount-cell {
  font-family: 'Roboto Mono', monospace;
  font-weight: 600;
  color: #00ffb3;
  text-align: right;
  transition: all 0.3s ease;
  padding: 4px 6px;
  border-radius: 4px;
}

:deep(.el-table__row:hover) .amount-cell {
  background-color: rgba(0, 255, 179, 0.1);
  transform: scale(1.05);
}

.count-cell {
  font-weight: 600;
  text-align: center;
  color: #00c9ff;
  background-color: rgba(0, 201, 255, 0.08);
  border-radius: 4px;
  padding: 4px 8px;
  display: inline-block;
  min-width: 40px;
}

/* 全局覆盖以确保没有白色背景 */
:deep(*) {
  background-color: transparent;
}

:deep(.el-table) {
  background-color: var(--bg-card-darker, #0f1023) !important;
  color: var(--text-primary, #e0e0ff);
}

:deep(.el-table__inner-wrapper) {
  background-color: var(--bg-card-darker, #0f1023) !important;
}

:deep(.el-table__header-wrapper),
:deep(.el-table__header-wrapper th.el-table__cell) {
  background-color: var(--bg-card-secondary, #191a32) !important;
  color: var(--text-primary, #e0e0ff);
  font-weight: 600;
}

:deep(.el-table__body-wrapper) {
  background-color: var(--bg-card-darker, #0f1023) !important;
}

:deep(.el-table__row) {
  background-color: var(--bg-card-darker, #0f1023) !important;
}

/* 自定义奇偶行样式 */
:deep(.odd-row) {
  background-color: var(--bg-card-darker, #0f1023) !important;
}

:deep(.even-row) {
  background-color: var(--bg-card-darker-alt, #171833) !important;
}

/* 确保所有单元格也都没有白色背景 */
:deep(.el-table--striped .el-table__body tr td),
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: inherit !important;
}

:deep(.el-table__row:hover td) {
  background-color: var(--bg-card-hover, #1e1f3d) !important;
}

/* 表格单元格内容样式优化 */
:deep(.el-table .cell) {
  line-height: 1.6;
  padding: 12px 8px;
  white-space: nowrap;
}

/* 数字列右对齐 */
:deep(.el-table td:nth-child(2)),
:deep(.el-table td:nth-child(3)),
:deep(.el-table td:nth-child(4)),
:deep(.el-table td:nth-child(5)) {
  text-align: right;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background-color: var(--scrollbar-thumb, #3a3b5a);
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background-color: var(--scrollbar-track, #1a1b38);
}

/* 确保表格外边框和单元格边框颜色正确 */
:deep(.el-table--border),
:deep(.el-table--group) {
  border-color: var(--border-color, #2a2a57) !important;
}

:deep(.el-table td), 
:deep(.el-table th.is-leaf) {
  border-bottom: 1px solid var(--border-color, #2a2a57) !important;
}

:deep(.el-table--border::after),
:deep(.el-table--border::before),
:deep(.el-table__inner-wrapper::after),
:deep(.el-table__inner-wrapper::before) {
  background-color: var(--border-color, #2a2a57) !important;
}

:deep(.el-table__fixed-right::before),
:deep(.el-table__fixed::before) {
  background-color: var(--border-color, #2a2a57) !important;
}

/* 固定列样式 */
:deep(.el-table .is-fixed-column--left) {
  border-right: 1px solid var(--border-color, #2a2a57) !important;
  box-shadow: 4px 0 8px rgba(0, 0, 0, 0.15) !important;
}

/* 修改表格空状态样式 */
:deep(.el-table__empty-block) {
  background-color: var(--bg-card-darker, #0f1023) !important;
  min-height: 100px;
}

:deep(.el-table__empty-text) {
  color: var(--text-secondary, #b8b8cc) !important;
}

/* 添加更强制的CSS规则 */
/* 强制覆盖任何可能的白色背景 */
:deep(.el-table) *:not(.growth-text):not(.error-text):not(.amount-cell):not(.count-cell):not(.month-cell) {
  background-color: transparent !important;
}

:deep(.el-table__body) tr:nth-child(odd) > td {
  background-color: var(--bg-card-darker, #0f1023) !important;
}

:deep(.el-table__body) tr:nth-child(even) > td {
  background-color: var(--bg-card-darker-alt, #171833) !important;
}

:deep(.el-table__cell) {
  background: none !important;
}

:deep(.el-table) .el-table__cell.is-hidden > * {
  visibility: visible !important;
}

:deep(.el-table__body) tr.current-row > td.el-table__cell {
  background-color: var(--bg-card-hover, #1e1f3d) !important;
}

/* 确保表格容器也没有白色背景 */
.table-container .el-table__body,
.table-container .el-table__footer,
.table-container .el-table__header {
  background-color: transparent !important;
}
</style> 